<template>
  <view class="container">
    <u-navbar
      v-if="type !== 1"
      title="发布房源转租信息"
      :autoBack="true"
      :fixed="true"
      :bgColor="'#ffffff'"
      :placeholder="true"
      :titleStyle="{
        color: '#333',
        fontSize: '16px',
      }"></u-navbar>

    <!-- 发布机会提示 -->
    <view class="publish-tip">
      {{ newtext }}
      <!-- 您当前还有
      <view class="num">1</view>
      次发布机会 -->
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <!-- 房子租金 -->
      <view class="form-item">
        <text class="label required">房子租金</text>
        <input
          class="input"
          type="number"
          v-model="form.money"
          placeholder="房租租金"
          placeholder-style="color: #999" />
        <text class="unit">元/月</text>
      </view>

      <!-- 转租户型 -->
      <view class="form-item arrow" @click="selectHouseType">
        <text class="label required">转租户型</text>
        <input
          class="input"
          v-model="form.houseType"
          placeholder="转租户型"
          disabled
          placeholder-style="color: #999" />
        <!-- <view class="value">{{ form.houseType || "单间" }}</view> -->
        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>
      <u-picker
        :show="showHouseType"
        :columns="columnsHouseType"
        @cancel="cancelHouseType"
        @confirm="confirmHouseType"
        keyName="text"></u-picker>
      <!-- 楼层 -->
      <view class="form-item">
        <text class="label required">楼层</text>
        <input
          class="input"
          type="text"
          v-model="form.floor"
          placeholder="楼层"
          placeholder-style="color: #999" />
      </view>
      <!-- 合同方式 -->
      <view class="form-item arrow" @click="selectContractType">
        <text class="label required">合同方式</text>
        <input
          class="input"
          v-model="form.contractType"
          placeholder="合同方式"
          placeholder-style="color: #999"
          disabled />
        <!-- <view class="value">{{ form.contractType || "重签合同" }}</view> -->
        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>
      <u-picker
        :show="showContractType"
        :columns="columnsContractType"
        @cancel="cancelContractType"
        @confirm="confirmContractType"
        keyName="text"></u-picker>

      <!-- 到期时间 -->
      <view class="form-item" @click="handTime">
        <text class="label">到期时间</text>
        <input
          class="input"
          v-model="form.expireDate"
          placeholder="到期时间"
          disabled
          placeholder-style="color: #999" />
        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>

      <!-- 类型 -->
      <view class="form-item arrow" @click="selectType">
        <text class="label required">类型</text>
        <input
          class="input"
          v-model="form.type"
          placeholder="类型"
          placeholder-style="color: #999"
          disabled />
        <!-- <view class="value">{{  || "整租" }}</view> -->
        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>
      <u-picker
        :show="showType"
        :columns="columnsType"
        @cancel="cancelType"
        @confirm="confirmType"
        keyName="text"></u-picker>

      <!-- 区域 -->
      <view class="form-item arrow" @click="selectArea">
        <text class="label required">区域</text>
        <input
          class="input"
          v-model="form.area"
          placeholder="区域"
          placeholder-style="color: #999"
          disabled />
        <!-- <view class="value">{{ form.area || "区域" }}</view> -->
        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>
      <u-picker
        :show="showArea"
        :columns="columnsArea"
        @cancel="cancelArea"
        @confirm="confirmArea"
        keyName="name"></u-picker>

      <!-- 位置 -->
      <view class="form-item arrow" @click="selectLocation">
        <text class="label">位置</text>
        <input
          class="input"
          v-model="form.location"
          placeholder="位置"
          placeholder-style="color: #999"
          disabled />
        <!-- <view class="value location">{{ form.location || "" }}</view> -->
        <u-icon name="map" color="#2979ff" size="16"></u-icon>
      </view>

      <!-- 描述 -->
      <view class="form-item textarea">
        <textarea
          v-model="form.description"
          placeholder="此处填写房子详情描述，参考格式：房子位置+户型+租金+房子其他详情信息"
          placeholder-style="color: #999"></textarea>
      </view>

      <!-- 图片上传 -->
      <view class="upload-section">
        <view class="upload-title">上传照片</view>
        <view class="upload-tip">最多上传9张图片</view>

        <view class="upload-content">
          <u-upload
            :fileList="fileList1"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
            multiple
            :maxCount="9">
            <view class="upload-item">
              <u-icon name="photo" size="28" color="#0095f8"></u-icon>
              <text>上传图片</text>
            </view>
          </u-upload>
        </view>
        <view class="upload-content" style="margin-top: 20rpx">
          <u-upload
            :fileList="fileList2"
            @afterRead="afterRead2"
            @delete="deletePic2"
            name="2"
            multiple
            v-if="!videoUrl"
            accept="video"
            :maxCount="1">
            <view class="upload-item">
              <image
                :src="video_icon"
                style="width: 56rpx; margin-bottom: 12rpx"
                mode="widthFix"></image>
              <text>上传视频</text>
            </view>
          </u-upload>
          <view style="width: 100%">
            <video
              v-if="videoUrl"
              :src="videoUrl"
              controls
              style="width: 100%; height: 240rpx">
              <u-icon
                name="trash"
                size="28"
                style="position: absolute; right: 20rpx; top: 10rpx"
                v-if="videoUrl"
                color="#0095f8"
                @click="deletePic2()"></u-icon>
            </video>
          </view>
          <!-- <view class="upload-item" @click="chooseImage">
            <u-icon name="photo" size="28" color="#0095f8"></u-icon>
            <text>上传图片</text>
          </view>
          <view class="upload-item" @click="uploadVideo">
            <image
              :src="video_icon"
              style="width: 56rpx; margin-bottom: 12rpx"
              mode="widthFix"></image>
            <text>上传视频</text>
          </view> -->
        </view>
      </view>

      <!-- 标签选择 -->
      <view class="tags-section">
        <view class="tags-list">
          <view
            class="tag-item"
            v-for="(tag, index) in tags"
            :key="index"
            :class="{ active: form.selectedTags.includes(tag) }"
            @click="toggleTag(tag)">
            {{ tag }}
          </view>
        </view>
        <view class="add-tag" @click="addNewTag">
          <u-icon name="plus" color="#2979ff" size="12"></u-icon>
          <text>新增标签</text>
        </view>
      </view>
      <u-modal
        :show="tagshow"
        title="新增标签"
        confirmText="确认"
        cancelText="取消"
        :showCancelButton="true"
        @cancel="tagCancel"
        @confirm="tagConfirm">
        <view class="slot-content">
          <u--input
            placeholder="请输入标签"
            border="surround"
            v-model="tagvalue"></u--input>
        </view>
      </u-modal>
      <!-- 联系方式 -->
	  <view class="section-title">联系方式</view>
      <view class="contact-section">
        <view class="form-item">
          <text class="label">联系人</text>
          <input
            class="input"
            v-model="form.contact"
            placeholder="请填写联系人姓名"
            placeholder-style="color: #999" />
        </view>
        <view class="form-item">
          <text class="label">手机号</text>
          <input
            class="input"
            type="number"
            v-model="form.phone"
            placeholder="请填写手机号"
            placeholder-style="color: #999" />
        </view>
        <view class="form-item">
          <text class="label">微信名</text>
          <input
            class="input"
            v-model="form.wechat"
            placeholder="请填写微信名"
            placeholder-style="color: #999" />
        </view>
      </view>
      <!-- :max-date="maxDate" -->
      <!-- <u-calendar
        :show="showCalendar"
        :min-date="minDate"
        :month-num="165"
        @confirm="confirmCalendar"
        @close="showCalendar = false"></u-calendar> -->
      <uni-calendar ref="calendar" :insert="false" @confirm="confirmCalendar" />
    </view>
    <!-- 提交按钮 -->
    <view class="submit-btn" @click="handleSubmit">确认发布</view>
  </view>
</template>

<script>
import {
  getHouseTypeList,
  getContractTypeList,
  getTypeList,
  publishSublease,
  getTagList,
  getArea2,
  getSendType,
} from "@/api/gent.js";
const d = new Date();
const year = d.getFullYear();
console.log(year);
let month = d.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
const date = d.getDate();
export default {
  props: ["type"],
  data() {
    return {
      maxDate: "2099-12-31", // 确保日期格式正确
      minDate: `${year}-${month}-${date}`,
      tabs: ["房屋转租", "便民广告", "商家优惠"],
      video_icon: this.$Config.HTTP_REQUEST_URL + "/img/icon30.png",
      currentTab: 0,
      form: {
        money: "",
        houseType: "",
        contractType: "",
        expireDate: "",
        type: "",
        area: "",
        location: "",
        description: "",
        contact: "",
        phone: "",
        wechat: "",
        selectedTags: [],
        longitude: "",
        latitude: "",
      },
      fileList: [],
      tags: ["免管理费", "免网费", "交通便利", "公寓", "民房", "民用水电"],
      showCalendar: false,
      showHouseType: false,
      showContractType: false,
      showType: false,
      showArea: false,
      columnsHouseType: [
        [
          {
            text: "单间",
            id: "1",
          },
          {
            text: "标间",
            id: "2",
          },
          {
            text: "一室一厅",
            id: "3",
          },
        ],
      ],
      columnsContractType: [
        [
          {
            text: "重签合同",
            id: "1",
          },
          {
            text: "首次签合同",
            id: "2",
          },
          {
            text: "续签合同",
            id: "3",
          },
        ],
      ],
      columnsType: [
        [
          {
            text: "整租",
            id: "1",
          },
          {
            text: "合租",
            id: "2",
          },
          {
            text: "短租",
            id: "3",
          },
        ],
      ],
      columnsArea: [
        [
          {
            text: "区域1",
            id: "1",
          },
          {
            text: "区域2",
            id: "2",
          },
          {
            text: "区域3",
            id: "3",
          },
        ],
      ],
      tagshow: false,
      tagvalue: "",
      fileList1: [],
      fileList2: [],
      videoUrl: "",
      newtext: "",
    };
  },
  mounted() {
    this.getGent();
    this.getContractType();
    this.getType();
    this.getTagList();
    this.getArea();
    this.getSendType();
  },
  methods: {
    handTime() {
      this.$refs.calendar.open();
    },
    async getSendType() {
      const res = await getSendType();
      if (res.response.statusCode === 200) {
        console.log(res.data.data.text);
        this.newtext = res.data.data.text;
      }
    },
    async getGent() {
      const res = await getHouseTypeList();
      if (res.response.statusCode === 200) {
        const vueReactiveArray = Object.keys(res.data.data).map((key) => {
          return {
            id: key,
            text: res.data.data[key],
          };
        });
        this.columnsHouseType = [[...vueReactiveArray]];
      }
    },

    async getArea() {
      const res = await getArea2({
        cid: 2,
      });
      if (res.response.statusCode === 200) {
        console.log(res.data.data, 23423);
        var ar = Object.entries(res.data.data).map(([key, value]) => ({
          name: value,
          id: key,
        }));
        this.columnsArea = [[...ar]];
      }
    },
    async getTagList() {
      const res = await getTagList();
      if (res.response.statusCode === 200) {
        this.tags = Object.values(res.data.data);
      }
    },

    async getContractType() {
      const res = await getContractTypeList();
      if (res.response.statusCode === 200) {
        const vueReactiveArray = Object.keys(res.data.data).map((key) => {
          return {
            id: key,
            text: res.data.data[key],
          };
        });
        this.columnsContractType = [[...vueReactiveArray]];
      }
    },
    async getType() {
      const res = await getTypeList();
      if (res.response.statusCode === 200) {
        const vueReactiveArray = Object.keys(res.data.data).map((key) => {
          return {
            id: key,
            text: res.data.data[key],
          };
        });
        this.columnsType = [[...vueReactiveArray]];
      }
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result.fullurl,
          })
        );
        fileListLen++;
      }
    }, // 删除视频
    deletePic2() {
      this.fileList2.splice(0, 1);
      this.videoUrl = "";
    },
    // 新增图片
    async afterRead2(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise2(lists[i].url);
        this.videoUrl = result.fullurl;
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result.fullurl,
          })
        );
        fileListLen++;
      }
    },
    uploadFilePromise2(url) {
      console.log(url, 234234);
      return new Promise((resolve, reject) => {
        const token = uni.getStorageSync("userInfo").token;
        uni.uploadFile({
          url: this.$Config.HTTP_REQUEST_URL + "/api/common/upload",
          fileType: "all",
          name: "file",
          filePath: url,
          header: {
            token: token,
          },
          success: (res) => {
            console.log(res.data, JSON.parse(res.data).data);
            setTimeout(() => {
              resolve(JSON.parse(res.data).data);
            }, 1000);
          },
        });
      });
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        const token = uni.getStorageSync("userInfo").token;
        uni.compressImage({
          src: url,
          quality: 50,
          success: (chooseImageRes) => {
            uni.uploadFile({
              url: this.$Config.HTTP_REQUEST_URL + "/api/common/upload",
              fileType: "all",
              name: "file",
              filePath: chooseImageRes.tempFilePath,
              header: {
                token: token,
              },
              success: (res) => {
                setTimeout(() => {
                  resolve(JSON.parse(res.data).data);
                }, 1000);
              },
            });
          },
        });
      });
    },

    switchTab(index) {
      this.currentTab = index;
    },
    selectHouseType() {
      // 选择户型
      this.showHouseType = true;
    },
    selectContractType() {
      // 选择合同方式
      this.showContractType = true;
    },
    selectType() {
      // 选择类型
      this.showType = true;
    },
    selectArea() {
      // 选择区域
      this.showArea = true;
    },
    selectLocation() {
      // wgs84 gcj02
      var that = this;
      wx.chooseLocation({
        type: "gcj02",
        success: (res) => {
          console.log(res);
          that.form.location = res.name;
          that.form.latitude = res.latitude;
          that.form.longitude = res.longitude;
        },
      });
    },
    cancelHouseType() {
      this.showHouseType = false;
    },
    confirmHouseType(e) {
      console.log(e);
      this.showHouseType = false;
      this.form.houseType = e.value[0].text;
      this.form.houseTypeId = e.value[0].id;
    },
    cancelContractType() {
      this.showContractType = false;
    },
    confirmContractType(e) {
      this.showContractType = false;
      this.form.contractType = e.value[0].text;
      this.form.contractTypeId = e.value[0].id;
    },
    cancelType() {
      this.showType = false;
    },
    confirmType(e) {
      this.showType = false;
      this.form.type = e.value[0].text;
      this.form.typeId = e.value[0].id;
    },
    cancelArea() {
      this.showArea = false;
    },
    confirmArea(e) {
      console.log(e, 33333);
      this.showArea = false;
      this.form.area = e.value[0].name;
      this.form.area_id = e.value[0].id;
    },
    confirmCalendar(date) {
      console.log(date);
      this.form.expireDate = date.fulldate;
      this.showCalendar = false;
    },

    toggleTag(tag) {
      const index = this.form.selectedTags.indexOf(tag);
      if (index > -1) {
        this.form.selectedTags.splice(index, 1);
      } else {
        this.form.selectedTags.push(tag);
      }
    },
    addNewTag() {
      // 添加新标签
      this.tagshow = true;
    },
    tagCancel() {
      // 添加新标签
      this.tagshow = false;
      this.tagvalue = "";
    },
    tagConfirm() {
      // 添加新标签
      console.log(this.tags);
      this.tagshow = false;
      if (this.tagvalue != "") {
        this.tags.push(this.tagvalue);
        this.tagvalue = "";
      }
    },
    async handleSubmit() {
      // 提交表单
      if (this.form.money == "") {
        return uni.showToast({
          title: "请输入房子租金",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.houseType == "") {
        return uni.showToast({
          title: "请选择转租户型",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.floor == "") {
        return uni.showToast({
          title: "请输入楼层",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.contractType == "") {
        return uni.showToast({
          title: "请选择合同方式",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.type == "") {
        return uni.showToast({
          title: "请选择类型",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.area == "") {
        return uni.showToast({
          title: "请选择区域",
          icon: "none",
          duration: 2000,
        });
      }
      var contcatarr = this.fileList1.concat(this.fileList2);
      console.log("提交表单", this.form, this.fileList1, this.fileList2);
      var arr = [];
      contcatarr.forEach((element, index) => {
        arr.push(element.url);
      });
      console.log(arr.join(","));
      const res = await publishSublease({
        area_id: this.form.area_id,
        money: this.form.money,
        house_type: this.form.houseTypeId,
        contract_type: this.form.contractTypeId,
        type: this.form.typeId,
        name: this.form.contact,
        phone: this.form.phone,
        wx_num: this.form.wechat,
        end_time: this.form.expireDate ? this.form.expireDate : "",
        lng: this.form.longitude,
        lat: this.form.latitude,
        address: this.form.location,
        desc: this.form.description,
        photos: arr.join(","),
        tags: this.form.selectedTags.join(","),
        floor: this.form.floor,
      });
      if (res.response.data.code === 1) {
        uni.showToast({
          title: "发布成功",
          icon: "none",
          duration: 2000,
        });
        setTimeout(() => {
          uni.reLaunch({
            url: "/pages/house-transfer/house-transfer",
          });
        }, 1000);
        // Object.keys(this.form).forEach((key) => {
        //   this.form[key] = "";
        // });
        // arr = [];
        // this.fileList1 = [];
        // this.fileList2 = [];
        // this.videoUrl = "";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f6fa;
  padding-bottom: constant(safe-area-inset-bottom);
  /* iOS 11.2 */
  padding-bottom: env(safe-area-inset-bottom);
  /* iOS 11.2 */
}

.publish-tip {
  display: flex;
  padding: 20rpx 24rpx;
  font-size: 24rpx;
  color: #999;
  .num {
    color: #ff0000;
  }
}

.form-content {
  padding: 0 24rpx;

  .form-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 24rpx;
    display: flex;
    align-items: center;

    &.arrow {
      padding-right: 24rpx;
    }

    .label {
      font-size: 28rpx;
      color: #333;
      margin-right: 24rpx;

      &.required::before {
        content: "*";
        color: #ff5a5f;
        margin-right: 4rpx;
      }
    }

    .input {
      flex: 1;
      font-size: 28rpx;
      text-align: right;
    }

    .unit {
      font-size: 28rpx;
      color: #999;
      margin-left: 16rpx;
    }

    .value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      text-align: right;

      &.location {
        color: #2979ff;
      }
    }

    &.textarea {
      padding: 24rpx;
      align-items: flex-start;

      textarea {
        width: 100%;
        height: 200rpx;
        font-size: 28rpx;
      }
    }
  }
}

.upload-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  .upload-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
  }

  .upload-tip {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 24rpx;
  }

  .upload-content {
    display: flex;
    // flex-wrap: wrap;
    // gap: 24rpx;

    .upload-item {
      width: 160rpx;
      height: 160rpx;
      background: #f5f6fa;
      border-radius: 8rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      text {
        font-size: 24rpx;
        color: #999;
        margin-top: 8rpx;
      }
    }
  }
}

.tags-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  .tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 24rpx;

    .tag-item {
      padding: 12rpx 24rpx;
      font-size: 24rpx;
      color: #666;
      background: #f5f5f5;
      border-radius: 4rpx;

      &.active {
        color: #2979ff;
        background: rgba(41, 121, 255, 0.1);
      }
    }
  }

  .add-tag {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #2979ff;

    text {
      margin-left: 8rpx;
    }
  }
}

	.section-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 24rpx;
	}

	.contact-section {
		.form-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 38rpx;
			margin-bottom: 24rpx;
		}
	}


.submit-btn {
  margin: 0 24rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #2979ff;
  border-radius: 44rpx;
  color: #fff;
  font-size: 32rpx;
}
</style>
